<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Session;
use app\model\SidebarNavDetail as NavDetailModel;

class CheckLogin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //验证用户登陆
        if(!Session::has('username')){
            return redirect((string)url('login/index'));
            Session::set('lastLink',$request->url());
        }else{
            //验证用户权限
            //获取登陆时写到session里的权限
            $userAuthLevel = Session::get('userAuthLevel');
            //获取当前的控制器
            $condition['controller'] = $request->controller();
            //获取当前的操作
            $condition['action'] = $request->action();

            //查询当前页面的权限
            $controller = NavDetailModel::where($condition)->find();

            if(!empty($controller)){
                //查询有权限的id数组
                $nav_detail_id_group = explode(",",Session::get('nav_detail'));

                //比对用户权限与页面权限，如果没有权限就返回登陆页
                if(in_array($controller['id'],$nav_detail_id_group)){
                    
                }else{
                    $id = $nav_detail_id_group[0];
                    $link = NavDetailModel::find($id);
                    $url = $link['controller'].'/'.$link['action'];
                    return redirect((string)url($url));
                    // echo "<script>alert('权限不足，返回上一页');history.go(-1);</script>";  

                }
            }
        }
        return $next($request);
    }
}
